import os
import time
from pprint import pprint
from tests.ry_roll_up_banner.common import constant
import pymysql
import requests

now = time.strftime("%Y%m%d-%H%M%S")  # 当前的时间
print("当前时间" + now)
host_url = constant.host_url
# 224商家后台账号
shop_userName = constant.shop_userName
shop_password = constant.shop_password
userId = constant.userId  # 商家后台的账号id

# 224大运营账户密码
j_username = constant.j_username
j_password = constant.j_password

# 因为每次运行都要创建一个商场就很麻烦了，就指定一个商场
mallId = constant.mallId
mallName = constant.mallName
cityId = constant.cityId  # 上海
floorId = constant.floorId
layoutId_yilabao = constant.layoutId_yilabao  # 电子易拉宝的配置id
# mac = constant.mac
mall_groupId = constant.mall_groupId  # 该商场的素材分组
layoutId_custom = constant.layoutId_custom  # 建站的配置id
appcode_yilabao = constant.appcode_yilabao  # appcode  易拉宝是rollScreen  ，建站的是mallCustomized
appcode_custom = constant.appcode_custom


cur_path = str(os.path.dirname(os.path.dirname(__file__)))
cur_path = cur_path.replace('\\', '/')
print("当前路径是" + str(cur_path))


# 获取商家后台的登录cookie
def shop_login():
    url = host_url + '/bsoms/user/ajaxLogin'

    header = {
        "Content-Type": "application/json;charset=UTF-8",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
    }

    data = {"userName": shop_userName, "password": shop_password, "verifyCode": "", "verifyCode1": "", "phone": "",
            "userPwd": "", "userPwd2": ""}
    r = requests.post(url=url, headers=header, json=data)
    # print(r.status_code, r.text)
    # print(r.headers)
    cookie = requests.utils.dict_from_cookiejar(r.cookies)
    # print(cookie)

    """
    cookie = r.headers['Set-Cookie'].split(',')[1].split(';')[0]
    print(cookie.strip())
    return cookie.strip()
    """
    BSST = cookie['BSST']
    JSESSIONID = cookie['JSESSIONID']
    print(cookie)
    return "BSST=" + BSST


# 获取大运营后台的登录cookie
def dayunying_login():
    url = host_url + '/ryoms/j_spring_security_check'
    header = {
        "Content-Type": "application/x-www-form-urlencoded",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }

    data = {"j_username": j_username, "j_password": j_password, "verifyCode": ""}
    r = requests.post(url=url, headers=header, data=data, allow_redirects=False)
    # print(r.status_code, r.text)
    # print(r.headers)
    print(r.cookies)
    # 获取requests请求返回的cookie   {'RYST': '8cc94b80534bc19d935164d101214dd0', 'JSESSIONID': '5346F96DB72D475701908EB19C735DEC'}
    cookie = requests.utils.dict_from_cookiejar(r.cookies)
    RYST = cookie['RYST']
    JSESSIONID = cookie['JSESSIONID']
    return "RYST=" + RYST


def ops_login():
    base_url = host_url + "/ops/user/login"
    header = {
        "Content-Type": "application/json;charset=UTF-8",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
    }

    data = {"userName": j_username, "password": j_password}
    r = requests.post(base_url, headers=header, json=data, allow_redirects=True)
    RYST = "RYST=" + r.cookies['RYST']
    print("方法获取的最新ops的cookie：" + RYST)
    return RYST


def create_device():
    print("先创建一个设备编号 提供给设备进行绑定")
    header = {
        "Cookie": ops_login(),
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 "
                      "Safari/537.36"}
    url = host_url + "/ops/machineCode/createDevice"
    data = {"machineNumInfo": {"createNum": "1", "machineDeviceType": 1, "machineOsType": "", "companyType": 0},
            "motherboardInfo": {"machineFactoryOwner": "视美泰", "machineCpu": "3399", "machineArm": "2G",
                                "machineHardDisk": "16G"},
            "machineScreenInfo": {"screenFactoryOwner": "LG", "screenModel": "LG型号", "screenSize": "43",
                                  "screenResolution": "2K", "screenBright": "200"},
            "machineExteriorInfo": {"machineSize": "", "machineColor": "", "surfaceMaterial": "", "machineProcess": "",
                                    "screenInstallationMethod": "", "machineInstallationMethod": ""},
            "machineOtherInfo": {"operateTemperature": "", "storageHumidity": "", "powerSupplyManufacturer": "",
                                 "powerSupplyModel": "", "builtInSpeaker": ""}, "machineDeviceExternalFacility": [
            {"externalFacilityIsExist": 1, "externalFacilityCode": "101", "model": ""},
            {"externalFacilityIsExist": 1, "externalFacilityCode": "102", "model": ""},
            {"externalFacilityIsExist": 1, "externalFacilityCode": "103", "model": ""},
            {"externalFacilityIsExist": 1, "externalFacilityCode": "105"},
            {"externalFacilityIsExist": 1, "externalFacilityCode": "106", "model": "", "antennaModel": ""},
            {"externalFacilityIsExist": 1, "externalFacilityCode": "107", "model": ""},
            {"externalFacilityIsExist": 1, "externalFacilityCode": "108", "model": ""},
            {"externalFacilityIsExist": 1, "externalFacilityCode": "109", "model": ""},
            {"externalFacilityIsExist": 1, "externalFacilityCode": "000", "externalFacilityFactoryOwner": "",
             "touchMode": ""}]}
    r = requests.post(url, headers=header, json=data)
    print(r.status_code, r.json())


def get_ops_machine_code():
    print("设备绑定获取一个设备编号,用作设备绑定/ops/machineCode/queryMachineSingleCode")
    create_device()  # 先创建一个编号，再绑定
    url = host_url + "/ops/machineCode/queryMachineSingleCode"
    header = {
        "Cookie": ops_login(),
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 "
                      "Safari/537.36"}
    data = {}
    r = requests.post(url, headers=header, json=data)
    print(r.status_code, r.json())
    result = r.json()
    code = result['result']['data']['code']
    print(code)
    return code


def create_machine(mac):
    serverUnbindMachine(mac)  # 先把设备mac解绑，然后再创建新设备
    print("设备绑定-添加一个设备/ops/machineManage/addMachine，并返回设备编号")
    header = {
        "Cookie": ops_login(),
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 "
                      "Safari/537.36"}
    machine_name = "taozhen自动化测试设备" + now
    print(machine_name)
    create_device()  # 创建一个设备 code
    code = get_ops_machine_code()
    address = "taozhen自动化测试设备位置" + now
    data = {
        "info": {
            "id": "",
            "name": machine_name,
            "machineType": 1,
            "code": code,
            "owner": 1,
            "customerType": 0,
            "mallId": mallId,
            "mallName": mallName,
            "floorId": floorId,
            "address": address,
            "screenSize": "",
            "mac": mac,
            "enterTimeStr": "",
            "osType": 1,
            "state": 1,
            "groupId": "",
            "guardStatus": "",
            "lineControl": "",
            "onAndOffStatus": "",
            "infraRed": "",
            "rfid": "",
            "coordinateX": "123",
            "coordinateY": "231"
        },
        "purchase": {
            "supplierName": "",
            "supplierAddress": "",
            "contacts": "",
            "contactsPhone": "",
            "purchaseTime": "",
            "guaranteeTime": ""
        }
    }
    url = host_url + "/ops/machineManage/addMachine"
    r = requests.post(url, headers=header, json=data)
    print(r.status_code, r.json())
    return code


def packAllData():
    print("为该商场打全量包  " + str(mallId))
    header = {
        "Cookie": dayunying_login(),
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 "
                      "Safari/537.36"}
    url = host_url + "/easy-smart/dataPacket/packAllData"
    data = {"hasAd": False, "mallId": mallId, "remark": ""}
    r = requests.post(url, headers=header, json=data)
    print(r.status_code, r.json())


# {"appCode":"rollScreen","mallId":"5c92f95c6bcb4aa7c6908010","auditState":2,"pageSize":1000}
def getMallAppCaseList(appcode):
    print("商家后台应用中心-获取应用模板caseid  商场id是  " + str(mallId))
    url = host_url + '/easy-smart-basic/mallApplication/getMallAppCaseList'
    header = {
        "Cookie": shop_login(),
        "Content-Type": 'application/json',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }

    data = {"appCode": appcode, "mallId": mallId, "auditState": 2, "pageSize": 1000}
    r = requests.post(url=url, headers=header, json=data)
    print(r.json())
    return r.json()


def shop_saveAppCase(caseId, machineId, layoutId_type):
    print("商家后台应用中心-配置设备，关联应用和模板    " + str(mallId))
    url = host_url + '/easy-smart-basic/machine/saveAppCase'
    header = {
        "Cookie": shop_login(),
        "Content-Type": 'application/json',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }

    data = {"caseId": caseId, "appId": layoutId_type, "machineIdList": [int(machineId)], "mallId": mallId, "id": ""}
    print("参数是 --> " + str(data))
    r = requests.post(url=url, headers=header, json=data)
    print(r.json())
    assert r.json()['meta']['msg'] == 'success'

def updateData_judgeHasUpdate():
    print("检测该商城一键更新是否可用，置灰的返回false，高亮返回True   商场id是  " + str(mallId))
    url = host_url + '/easy-smart/updateData/judgeHasUpdate'
    header = {
        "Cookie": shop_login(),
        "Content-Type": 'application/json',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    data = {"mallId": mallId}
    r = requests.post(url=url, headers=header, json=data)
    print(r.json())
    update_type = r.json()["result"]["data"]["hasUpdate"]  # 可更新的状态
    print("返回一键更新状态是否可用，true的话，可以执行一键更新，false不能执行")
    return update_type


def updateData_packUpdate():
    print("商家一键更新，下发增量包，mallId是  " + str(mallId))
    update_type = updateData_judgeHasUpdate()
    assert update_type == True  # 校验一键更新状态是否为True
    url = host_url + '/easy-smart/updateData/packUpdate'
    header = {
        "Cookie": shop_login(),
        "Content-Type": 'application/json',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    data = {"mallId": mallId}
    r = requests.post(url=url, headers=header, json=data)
    pprint(r.json(), indent=2)
    if r.json()['meta']['msg'] == 'success':
        print("一键更新成功")
    else:
        print("一键更新失败")
    return r.json()


def serverUnbindMachine(mac):
    print("根据mac查询是否被绑定，被绑定了就给他解绑,该mac是  " + str(mac))
    header = {
        "Cookie": ops_login(),
        "Content-Type": 'application/json',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    url_machine = host_url + '/ops/machineManage/queryMachine'
    data = {"machineNameOrCode": mac, "currentPage": 1, "pageSize": 20, "page": 1}
    r_query = requests.post(url=url_machine, headers=header, json=data)
    result_query = r_query.json()
    print(result_query)
    # 如果返回值的data里是空的，那就走下去。如果有machine数据，就找到machineid并解绑他
    # 解绑mac，查询该mac，如果该mac已经绑定了，就解除它
    if result_query['result']['data'] != []:
        machineId_query = result_query['result']['data'][0]['id']  # 查询到被该mac绑定的设备id
        print(machineId_query)
        url_unbind = host_url + '/ops/machineManage/serverUnbindMachine'
        data_unbind = {"machineId": machineId_query}
        r_unbind = requests.post(url=url_unbind, headers=header, json=data_unbind)
        print("已解绑该mac  " + mac)
    else:
        print("该mac   " + mac + "   没有被任何设备绑定，不需要解绑")


def get_machineId(machine_code):
    print("根据设备code，返回machineId")
    url = host_url + '/ops/machineManage/queryMachine'
    header = {
        "Cookie": ops_login(),
        "Content-Type": 'application/json',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    data = {"machineNameOrCode": machine_code, "currentPage": 1, "pageSize": 20, "page": 1}
    r = requests.post(url=url, headers=header, json=data)
    print(r.json())
    machine_Id = r.json()['result']['data'][0]['id']
    print("根据设备编号获取到的machineId是    " + str(machine_Id))
    return machine_Id


def delete_machine(code):
    print("根据设备编号删除新增的设备 设备编号是  " + str(code))
    db = pymysql.connect(host=constant.host, port=constant.port, user=constant.mysql_username,
                         passwd=constant.mysql_password, db="ry_andriod_terminal")
    cursor = db.cursor()  # 获取操作游标
    # cursor.execute("select id from machine where code=" + code)
    # 多表删除
    # DELETE t1 FROM t1,t2 WHERE t1.id=t2.id 或DELETE FROM t1 USING t1,t2 WHERE t1.id=t2.id
    sql1 = 'DELETE machine_expand FROM machine LEFT JOIN machine_expand ON machine.id=machine_expand.machine_id WHERE machine.code="%s"' % code
    sql2 = 'DELETE machine FROM machine LEFT JOIN machine_expand ON machine.id=machine_expand.machine_id WHERE machine.code="%s"' % code
    cursor.execute(sql1)
    cursor.execute(sql2)
    db.commit()
    cursor.close()  # 关闭游标
    db.close()  # 关闭数据库
    print("删除设备编号" + code)


def upload_file():
    print("上传图片")
    url = host_url + "/easy-smart/bsFileUpload/uploadFile"
    header = {
        # "Content-Type": "image/jpeg",
        "Content-Type": 'application/json',
        # "Content-Type": 'multipart/form-data; boundary=----WebKitFormBoundaryUPADoEbDqR4rhvCG',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
        "X-Requested-With": "XMLHttpRequest"
    }
    file = {"file": open("D:\\pydj\\ry_roll_up_banner\\photo.jpg", "rb")}
    r = requests.post(url=url, headers=header, files=file)
    print(r.json())
    image_url = r.json()['result']['data'][0]['url']
    print("上传图片返回图片链接为    " + str(image_url))
    return image_url


def add_mall_image(image_url):
    print("添加图片到商场里，图片链接是    " + str(image_url))
    url = host_url + "/easy-smart-basic/sourceManage/addBsSource"
    header = {
        "Cookie": shop_login(),
        "Content-Type": 'application/json',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    data = {"mallId": mallId, "dataList": [{"thumbnail": image_url,
                                            "name": "photo.jpg",
                                            "url": image_url,
                                            "format": "jpg", "groupId": mall_groupId, "size": 4016771,
                                            "type": 1, "attribute": "1920*1080"}]}
    r = requests.post(url=url, headers=header, json=data)
    assert r.json()['meta']['msg'] == "success"
    print("添加图片到商场成功")


def install_rongyi_launcher():
    print("安装容易桌面")
    rongyi_launcher_path = cur_path + "/data/com.rongyi.launcher_4.00.11.000_V4.00.11.00_202007131354_224.apk"
    os.system("adb install -r " + rongyi_launcher_path)


def delete_rongyi_launcher():
    print("卸载容易桌面+删除容易桌面数据")
    os.system("adb uninstall com.rongyi.launcher")
    os.system("adb shell rm -rf /sdcard/rongyi/")


def delete_mall_all_machine():
    print("删除该商场下的所有设备    " + str(mallId))
    url = host_url + "/easy-smart-basic/machine/list"
    header = {
        "Cookie": shop_login(),
        "Content-Type": 'application/json',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    data = {"currentPage": 1, "mallId": mallId, "pageSize": 100, "terminalCode": "",
            "terminalName": "", "online": "2", "groupId": "", "resolution": "", "shopIds": []}
    r = requests.post(url=url, headers=header, json=data)
    machine_list = []
    machine_data = r.json()['result']['data']['machines']#['code']
    for i in machine_data:
        machine_list.append(i['code'])
    print(machine_list)
    for j in machine_list:
        delete_machine(j)  # 删除
    print("删除完成该商场下的所有设备    " + str(mallId))

    # delete_machine(code)


def replace_string(str_A, str_B):
    f = open("custom_full.txt")
    str = f.read().replace(str_A, str_B)


# 素材上传，已久关联到商场  todo
# 生成设备machine，如果配置模板失败的话，删除该设备 todo
# shop_login()
# dayunying_login()
# ops_login()
# create_device()
# get_ops_machine_code()
# packAllData()
# updateData_judgeHasUpdate()
# updateData_packUpdate()
# serverUnbindMachine(mac)
# create_machine()
# updateData_packUpdate()
# serverUnbindMachine(mac)
# m = create_machine()
# get_machineId(m)
# delete_machine(code)
# install_rongyi_launcher()
"""
code = create_machine()
ma_id = get_machineId(code)
shop_saveAppCase(add_yilabao_case(), ma_id)
updateData_packUpdate()
"""

# updateData_judgeHasUpdate()
# install_rongyi_launcher()
# delete_rongyi_launcher()